<!-- 地址信息Header测试页面 -->
<template>
  <view class="min-h-screen bg-gray-50 p-6">
    <!-- 页面标题 -->
    <view class="mb-8">
      <text class="text-[36rpx] font-bold text-gray-900 text-center">地址信息Header测试</text>
    </view>

    <!-- 当前地址信息 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">当前地址信息</view>
      <view class="space-y-3 text-[24rpx] text-gray-700">
        <view class="flex justify-between">
          <text>完整地址：</text>
          <text class="font-medium text-blue-600">{{ fullAddress }}</text>
        </view>
        <view class="flex justify-between">
          <text>省份：</text>
          <text class="font-medium">{{ locationObj.address_component?.province || '未获取' }}</text>
        </view>
        <view class="flex justify-between">
          <text>城市：</text>
          <text class="font-medium">{{ locationObj.address_component?.city || '未获取' }}</text>
        </view>
        <view class="flex justify-between">
          <text>区县：</text>
          <text class="font-medium">{{ locationObj.address_component?.district || '未获取' }}</text>
        </view>
        <view class="flex justify-between">
          <text>经纬度：</text>
          <text class="font-medium text-[20rpx]">
            {{ locationObj.location?.lat ? `${locationObj.location.lat}, ${locationObj.location.lng}` : '未获取' }}
          </text>
        </view>
      </view>
    </view>

    <!-- 测试按钮 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">测试请求</view>
      <view class="space-y-4">
        <view class="flex flex-col gap-3">
          <nut-button
            type="primary"
            size="large"
            class="w-full"
            @click="testGetRequest"
            :loading="loading.get"
          >
            测试GET请求
          </nut-button>
          
          <nut-button
            type="primary"
            size="large"
            class="w-full"
            @click="testPostRequest"
            :loading="loading.post"
          >
            测试POST请求
          </nut-button>
          
          <nut-button
            type="default"
            size="large"
            class="w-full"
            @click="testUserInfoRequest"
            :loading="loading.userInfo"
          >
            测试用户信息请求
          </nut-button>
        </view>
      </view>
    </view>

    <!-- 请求结果 -->
    <view v-if="requestResults.length > 0" class="bg-white rounded-2xl p-6 shadow-sm">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">请求结果</view>
      <view class="space-y-4">
        <view 
          v-for="(result, index) in requestResults" 
          :key="index"
          class="border border-gray-200 rounded-xl p-4"
        >
          <view class="flex items-center justify-between mb-2">
            <text class="text-[28rpx] font-medium text-gray-800">{{ result.method }} {{ result.url }}</text>
            <text class="text-[24rpx] text-gray-500">{{ result.timestamp }}</text>
          </view>
          
          <view class="space-y-2">
            <view class="flex items-start">
              <text class="text-[24rpx] text-gray-600 w-[120rpx] flex-shrink-0">状态：</text>
              <text 
                class="text-[24rpx] font-medium"
                :class="result.success ? 'text-green-600' : 'text-red-600'"
              >
                {{ result.success ? '成功' : '失败' }}
              </text>
            </view>
            
            <view class="flex items-start">
              <text class="text-[24rpx] text-gray-600 w-[120rpx] flex-shrink-0">地址Header：</text>
              <text class="text-[24rpx] text-blue-600 flex-1 break-all">{{ result.addressHeader }}</text>
            </view>
            
            <view v-if="result.error" class="flex items-start">
              <text class="text-[24rpx] text-gray-600 w-[120rpx] flex-shrink-0">错误信息：</text>
              <text class="text-[24rpx] text-red-600 flex-1">{{ result.error }}</text>
            </view>
            
            <view v-if="result.response" class="flex items-start">
              <text class="text-[24rpx] text-gray-600 w-[120rpx] flex-shrink-0">响应数据：</text>
              <text class="text-[22rpx] text-gray-700 flex-1 break-all">{{ JSON.stringify(result.response) }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 功能说明 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mt-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">功能说明</view>
      <view class="space-y-3 text-[24rpx] text-gray-700">
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            1
          </view>
          <text class="flex-1">所有请求的header中会自动添加address参数，包含用户当前位置信息</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            2
          </view>
          <text class="flex-1">地址信息格式：省份 城市 区县（如：广东省 深圳市 南山区）</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            3
          </view>
          <text class="flex-1">如果未授权定位，address参数值为"未授权定位"</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            4
          </view>
          <text class="flex-1">后端可以通过header中的address参数获取用户位置信息</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'
import Taro from '@tarojs/taro'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/store/user'
import { get, post } from '@/utils/request'

// 用户store
const userStore = useUserStore()
const { locationObj } = storeToRefs(userStore)

// 响应式数据
const loading = ref({
  get: false,
  post: false,
  userInfo: false
})

const requestResults = ref<Array<{
  method: string
  url: string
  success: boolean
  addressHeader: string
  error?: string
  response?: any
  timestamp: string
}>>([])

// 计算完整地址
const fullAddress = computed(() => {
  if (!locationObj.value || !locationObj.value.address_component) {
    return '未授权定位'
  }
  
  const { address_component } = locationObj.value
  const parts = []
  
  if (address_component.province) parts.push(address_component.province)
  if (address_component.city) parts.push(address_component.city)
  if (address_component.district) parts.push(address_component.district)
  
  return parts.length > 0 ? parts.join(' ') : '未授权定位'
})

/**
 * 构建地址字符串（与request.ts中的逻辑一致）
 */
const buildAddressString = () => {
  if (!locationObj.value || !locationObj.value.address_component) {
    return '未授权定位'
  }
  
  const { address_component } = locationObj.value
  const parts = []
  
  if (address_component.province) parts.push(address_component.province)
  if (address_component.city) parts.push(address_component.city)
  if (address_component.district) parts.push(address_component.district)
  
  return parts.length > 0 ? parts.join(' ') : '未授权定位'
}

/**
 * 添加请求结果
 */
const addRequestResult = (method: string, url: string, success: boolean, addressHeader: string, error?: string, response?: any) => {
  requestResults.value.unshift({
    method,
    url,
    success,
    addressHeader,
    error,
    response,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 只保留最近10条记录
  if (requestResults.value.length > 10) {
    requestResults.value = requestResults.value.slice(0, 10)
  }
}

/**
 * 测试GET请求
 */
const testGetRequest = async () => {
  loading.value.get = true
  const addressHeader = buildAddressString()
  
  try {
    const response = await get('/test/get', { test: 'address header' })
    addRequestResult('GET', '/test/get', true, addressHeader, undefined, response)
    
    Taro.showToast({
      title: 'GET请求成功',
      icon: 'success',
      duration: 2000
    })
  } catch (error: any) {
    addRequestResult('GET', '/test/get', false, addressHeader, error.message || '请求失败')
    
    Taro.showToast({
      title: 'GET请求失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    loading.value.get = false
  }
}

/**
 * 测试POST请求
 */
const testPostRequest = async () => {
  loading.value.post = true
  const addressHeader = buildAddressString()
  
  try {
    const response = await post('/test/post', { test: 'address header', timestamp: Date.now() })
    addRequestResult('POST', '/test/post', true, addressHeader, undefined, response)
    
    Taro.showToast({
      title: 'POST请求成功',
      icon: 'success',
      duration: 2000
    })
  } catch (error: any) {
    addRequestResult('POST', '/test/post', false, addressHeader, error.message || '请求失败')
    
    Taro.showToast({
      title: 'POST请求失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    loading.value.post = false
  }
}

/**
 * 测试用户信息请求
 */
const testUserInfoRequest = async () => {
  loading.value.userInfo = true
  const addressHeader = buildAddressString()
  
  try {
    const response = await post('/my/index')
    addRequestResult('POST', '/my/index', true, addressHeader, undefined, response)
    
    Taro.showToast({
      title: '用户信息请求成功',
      icon: 'success',
      duration: 2000
    })
  } catch (error: any) {
    addRequestResult('POST', '/my/index', false, addressHeader, error.message || '请求失败')
    
    Taro.showToast({
      title: '用户信息请求失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    loading.value.userInfo = false
  }
}
</script>
